<template>
  <div class="clearfix">
  <a-upload
    name="file"
    :action="uploadAction"
    @preview="handlePreview"
    @change="handleChange"
    :headers="headers"
    :data="content"
    :beforeUpload="beforeUpload"
    :multiple="isMultiple"
    :show-upload-list="false"
  >
<!--    <img-->
<!--      v-if="!isMultiple && picUrl"-->
<!--      :src="getAvatarView()"-->
<!--      style="max-width: 130px"-->
<!--    />-->
    <el-button size="small" type="primary" style="height: 35px;margin-top: -3px;margin-right: -5px" >上传图片</el-button>
  </a-upload>
<!--    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel" style="z-index:999"  >-->
<!--      <img alt="example" style="width: 100%;z-index:999" :src="previewImage"  />-->
<!--    </a-modal>-->
  </div>
</template>

<script>
  import Vue from "vue";
  import api from '@/api/api'
  import store from "@/store";

const uidGenerator = () => {
  return "-" + parseInt(Math.random() * 10000 + 1, 10);
};
const getFileName = (path) => {
  if (path.lastIndexOf("\\") >= 0) {
    let reg = new RegExp("\\\\", "g");
    path = path.replace(reg, "/");
  }
  return path.substring(path.lastIndexOf("/") + 1);
};
  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }
export default {
  name: "editoruploadImg",
  data() {
    return {
      uploadAction: api.url.uploadFile,
      uploadLoading: false,
      picUrl: false,
      headers: {'Authori-zation': !store.getters.token?sessionStorage.getItem('token'):store.getters.token},
      fileList: [],
      previewImage: "",
      previewVisible: false,
      bizData: {},
      // filesList:[]
    };
  },
  props: {
    text: {
      type: String,
      required: false,
      default: "上传",
    },
    /*这个属性用于控制文件上传的业务路径*/
    bizPath: {
      type: String,
      required: false,
      default: "image",
    },
    content: {
      type: Object,
      required: false,
    },
    fileListValue: {
      type: String,
      required: false,
      default:''
    },
    value: {
      type: [String, Array],
      required: false,
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false,
    },
    isMultiple: {
      type: Boolean,
      required: false,
      default: false,
    },
    maxLength: {
      type: Number,
      required: false,
      default:1
    },
  },
  watch: {
    value(val) {
     // console.error("aaaaaaaaaa",val)
      if (val instanceof Array) {
       // console.error("bbbb",val)

        this.initFileList(val.join(","));
      } else {
        //console.error("ccccc",val)

        if (!val || val.length == 0 || val == undefined) {
          // debugger;
          this.picUrl = false;
          this.fileList = [];
          return;
        }

        if (this.fileList.length>0){
          this.initFileList(this.fileList.map(item => {
            return item.url
          }).join(","));
        }
        else {
          this.initFileList(val);
        }
      }
    },
  },
  mounted() {
  //  console.error("aaa",this.fileListValue)
    this.initFileList(this.fileListValue)
  },
  methods: {
    getFileAccessHttpUrl (avatar, subStr) {
      if (!subStr) subStr = 'http'
      if (avatar && avatar.startsWith(subStr)) {
        return avatar
      } else {
        if (avatar && avatar.length > 0 && avatar.indexOf('[') == -1) {
          return window._CONFIG['staticDomainURL'] + '/' + avatar
        }
      }},
    initFileList(paths) {
      if (!paths || paths.length == 0 || paths == undefined) {
    //    debugger;
        this.picUrl = false;
        this.fileList = [];
        return;
      }
      this.picUrl = true;
      let addFileList = [];
      let arr = paths.split(",");
      for (var a = this.fileList.length; a < arr.length; a++) {
        let url = this.getFileAccessHttpUrl(arr[a]);
        this.fileList.push({
          uid: uidGenerator(),
          name: getFileName(arr[a]),
          status: "done",
          url: url,
          response: {
            status: "history",
            message: arr[a],
          },
        });
      }
      //this.fileList.push(addFileList) ;
      //console.error("this.fileList",this.fileList)
    },
    beforeUpload: function (file) {
      var fileType = file.type;
      if (fileType.indexOf("image") < 0) {
        this.$message.warning("请上传图片");
        return false;
      }
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'|| file.type === 'image/jpg';
      if (!isJpgOrPng) {
        this.$message.error('图片仅支持jpg、jpeg、png格式!');
      }
      const isLt2M = file.size / 1024 / 1024 > 2;
      if (isLt2M) {
        this.$message.error('图片大小不能超过2MB!');
      }
      return isJpgOrPng && !isLt2M;
    },
    handleChange(info) {
      this.picUrl = false;
      let fileList = info.fileList;
    //  console.error(info.file.status )
      if (info.file.status === "done") {
        // debugger;

        if (info.file.response.code==200) {
         // console.info(info.file.response);
          info.file.response.message = info.file.response.data.url;
          if (info.file.response.data.compress){
            this.$message.success('当前图片已压缩:'+info.file.response.data.filesize+'KB');
          }else {
            this.$message.warning('当前图片未压缩:'+info.file.response.data.filesize+'KB');
          }
          this.picUrl = true;
          fileList = fileList.map((file) => {
            if (file.response) {
              file.url = file.response.message;
            }
            return file;
          });
        }
      } else if (info.file.status === "error") {
        this.$message.error('上传图片失败');
      } else if (info.file.status === "removed") {
        this.handleDelete(info.file);
      }
    if (info.file.status !=undefined){
      this.fileList = fileList;
    }

      // if (this.fileList.length >= this.maxLength) {
      //   this.disabled = true;
      // }
      if (info.file.status === "done" || info.file.status === "removed") {
        this.handlePathChange();
      }
    },
    // 预览
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.thumbUrl;
      this.previewVisible = true;
    },
    getAvatarView() {
      if (this.fileList.length > 0) {
        let url = this.fileList[0].url;
        //console.error(url)
        return this.getFileAccessHttpUrl(url);
      }
    },
    handlePathChange() {
      // let uploadFiles = this.fileList;
      // let path = "";
      // if (!uploadFiles || uploadFiles.length == 0) {
      //   path = "";
      // }
      // let arr = [];
      // if (!this.isMultiple) {
      //   arr.push(uploadFiles[uploadFiles.length - 1].response.message);
      // } else {
      //   for (var a = 0; a < uploadFiles.length; a++) {
      //     arr.push(uploadFiles[a].response.message);
      //   }
      // }
      // if (arr.length > 0) {
      //   path = arr.join(",");
      // }
   //   console.error("path",path)
   //    this.$message.success(this.fileList.map(item => {
   //      return item.url
   //    }).join(","));

      // let arr = [];
      // if(img.length>10) return this.$message.warning("最多选择10张图片！");
      // img.map((item) => {
      //   arr.push(item.sattDir)
      // });
      // console.log(arr);
     // _this.$emit('successCBK', arr)

      this.$emit("successCBK", this.fileList.map(item => {
        return item.url
      }));
    },
    handleDelete(file) {
      //如有需要新增 删除逻辑
      console.log(file);
    },
    handleCancel() {
      this.close();
      this.previewVisible = false;
    },
    close() {},
  },
  model: {
    prop: "value",
    event: "change",
  },
};
</script>

<style scoped>
</style>
